<template>
	<view>
		<index @ShowNews="ShowNews" v-if="PageCur=='index'"></index>
		<home v-if="PageCur=='home'"></home>
		<qrcode ref="qrcode" v-if="PageCur=='qrcode'"></qrcode>
		<spare v-if="PageCur=='spare'"></spare>
		<spareV2 v-if="PageCur=='spareV2'"></spareV2>
		<task v-if="PageCur=='task'"></task>
		<me v-if="PageCur=='me'"></me>

		<view class="box">
			<view class="cu-bar tabbar bg-white shadow foot">
				
				<view v-if="tabbar.includes('order')" class="action" @click="NavChange" data-cur="index">
					<view class='cuIcon-cu-image'>
						<view v-if="counts.SceneCount>0" class="cu-tag badge">{{counts.SceneCount}}</view>
						<image v-if="PageCur=='index'" :src="images.index_cur"></image>
						<image v-if="PageCur != 'index'" :src="images.index"></image>
					</view>
					<view :class="PageCur=='index'?'color_main':'text-gray'">维修工单</view>
				</view>
				
				<view v-if="tabbar.includes('task')" class="action" @click="NavChange" data-cur="task">
					<view class='cuIcon-cu-image'>
						<image v-if="PageCur=='task'" :src="images.task_cur"></image>
						<image v-if="PageCur != 'task'" :src="images.task"></image>
					</view>
					<view :class="PageCur==='task'?'color_main':'text-gray'">设备点检</view>
				</view>

				<view v-if="tabbar.includes('home')"  @click="NavChange" class="action text-gray add-action" data-cur="home">
					<image class="logo_btn" mode="widthFix" :src="logo"></image>
					<view :class="PageCur=='home'?'color_main':'text-gray'">工作台</view>
				</view>
				
				<view v-if="tabbar.includes('spareV1')" class="action" @click="NavChange" data-cur="spare">
					<view class='cuIcon-cu-image'>
						<view v-if="counts.Outbound>0" class="cu-tag badge">{{counts.Outbound}}</view>
						<image v-if="PageCur=='spare'" :src="images.spare_cur"></image>
						<image v-if="PageCur != 'spare'" :src="images.spare"></image>
					</view>
					<view :class="PageCur=='spare'?'color_main':'text-gray'">备件</view>
				</view>
				
				<view v-if="tabbar.includes('spareV2')" class="action" @click="NavChange" data-cur="spareV2">
					<view class='cuIcon-cu-image'>
						<image v-if="PageCur=='spareV2'" :src="images.spare_cur"></image>
						<image v-if="PageCur != 'spareV2'" :src="images.spare"></image>
					</view>
					<view :class="PageCur=='spareV2'?'color_main':'text-gray'">备件</view>
				</view>
				
				<view v-if="tabbar.includes('scan')" class="action" @click="NavChange" data-cur="qrcode">
					<view class='cuIcon-cu-image'>
						<!--小红点 <view class="cu-tag badge">{{message}}</view> -->
						<image v-if="PageCur=='qrcode'" :src="images.scan_cur"></image>
						<image v-if="PageCur != 'qrcode'" :src="images.scan"></image>
					</view>
					<view :class="PageCur=='qrcode'?'color_main':'text-gray'">定期巡检</view>
				</view>
				
				<view v-if="tabbar.includes('me')" class="action" @click="NavChange" data-cur="me">
					<view class='cuIcon-cu-image'>
						<image v-if="PageCur=='me'" :src="images.me_cur"></image>
						<image v-if="PageCur != 'me'" :src="images.me"></image>
					</view>
					<view :class="PageCur=='me'?'color_main':'text-gray'">我的</view>
				</view>

			</view>
		</view>
	</view>
</template>

<script>
    import request from '@/common/request.js';
	import index from "../qrcode/scene/inedx.vue";	//工单页面
	import home from "pages/qrcode/main/main_v1";	//主页
	import qrcode from "../qrcode/qrcodejob/index.vue";	//巡检页面
	import spare from "pages/spare/main";	//备件页面
	import spareV2 from "pages/spare/main_v2";	//备件页面
	///import task from "pages/mytask/task";	//我的任务
	import task from "pages/mytask/SpotChcekList";	//我的任务
	import me from "pages/index/me_out";	//我的
	export default {
		components: {
			index,
			home,
			qrcode,
			spare,
			spareV2,
			task,
			me,
		},
		data() {
			return {
				images:{
					index:this.$request22.baseUrl1+'/Resource/sg/tabBar/index.png',
					index_cur:this.$request22.baseUrl1+'/Resource/sg/tabBar/index_cur.png',
					me:this.$request22.baseUrl1+'/Resource/sg/tabBar/me.png',
					me_cur:this.$request22.baseUrl1+'/Resource/sg/tabBar/me_cur.png',
					scan:this.$request22.baseUrl1+'/Resource/sg/tabBar/scan.png',
					scan_cur:this.$request22.baseUrl1+'/Resource/sg/tabBar/scan_cur.png',
					spare:this.$request22.baseUrl1+'/Resource/sg/tabBar/spare.png',
					spare_cur:this.$request22.baseUrl1+'/Resource/sg/tabBar/spare_cur.png',
					task:this.$request22.baseUrl1+'/Resource/sg/tabBar/task.png',
					task_cur:this.$request22.baseUrl1+'/Resource/sg/tabBar/task_cur.png',
				},
				logo:this.$request22.baseUrl1+'/Resource/sg/logo.png',
				counts:{
					SceneCount:0,
					Outbound:0,
					yujing:0,
					guoliang:0
				},
				PageCur: 'home',
				message: '2',
				openId:'',
				access_token:'',
				tip:"我是提示",
				duration:1,
				AddPosition:{
					JobId:0,
					Longitude:'',
					Latitude:''
				},
				addEntity:{
					JobId:0,
					Longitude:'',
					Latitude:'',
					LoginType:1
				},
				timer:null,
				nowTime: '', //日期
				nowTime2: '', //时间 
				tabbar:[
					'order','','home','','scan',''
				]
			};
		},
		// 分享小程序
		onShareAppMessage(res) {
			return {
				title: this.$request22.projectName+'-'+this.$request22.projectDesc,
			};
		},
		onLoad(option){
			console.log('onLoad-tabbar') 
			
			let that=this
			that.updateApplet()
			
			if(option.PageCur != '' && option.PageCur != undefined && option.PageCur != null){
				that.PageCur=option.PageCur
			}else{
				that.PageCur='home'
			}
			//有jobId自动缓存赋值，不需要手动选择
			let jobId=option.jobId
			that.setJobStorage(jobId);
			//有工单id，自动跳转工单详情
			let sceneId=option.sceneId
			if(sceneId != '' && sceneId != undefined && sceneId != null&& sceneId != '0'){
				uni.setStorage({
					key:'SceneLink',
					data:{
						sceneId:sceneId,
						type:'goSceneDetail'
					},
					success() {
					}
				})
			}
			uni.getStorage({
				key: 'userdata',
				success: function (resuserdata) {
					console.log('userdata')
					let CustomerLogo=resuserdata.data.CustomerLogo
					if(CustomerLogo!=null&&CustomerLogo!=''){
						that.logo=resuserdata.data.CustomerLogo
					}
					if(resuserdata.data.IsWeChatAutoRegister==1){
						that.updateTabbar()
					}else{
						that.tabbar=['order','','','','','me']
						that.PageCur='index'
						console.log('PageCur:'+that.PageCur)
					}
				}
			});
			
			
			//解析直接巡检点位
			if (option.InspectionQrcodeId) {
				// 跳转到qrcode页面并传递参数
				that.PageCur = 'qrcode'; // 确保切换到qrcode组件
				// 可能需要使用setTimeout等待组件渲染
				setTimeout(() => {
					this.$refs.qrcode.DirectInspection(option.InspectionQrcodeId);
				}, 0);
			}
		},
		onShow(){
			console.log('onShow-tabbar')
			this.getSceneCount();
			this.GetSpareCounts();
			
			// 读取缓存
			let Qrcode_Topic_Back_Refresh = uni.getStorageSync('Qrcode_Topic_Back_Refresh');
			if (Qrcode_Topic_Back_Refresh) {
			    this.$refs.qrcode.handleTopicSuccess(Qrcode_Topic_Back_Refresh); // 传递对象
			    uni.removeStorageSync('Qrcode_Topic_Back_Refresh'); // 清除缓存
			}
			// if (uni.getStorageSync('Qrcode_Topic_Back_Refresh')) {
			// 	uni.removeStorageSync('Qrcode_Topic_Back_Refresh'); // 清除标记
			// 	this.$refs.qrcode.handleTopicSuccess(); // 通知qrcode.vue
			// }
		},
		mounted() {
			console.log('mounted-tabbar')
		},
		onHide(){
			console.log('onHide-tabbar')
		},
		methods: {
			updateTabbar(){
				let that=this
				let opts = {
					url: 'api/GetMiniProgramMenu',
					method: 'post'
				};
				request.httpTokenNotCheckRequest(opts).then(res => {
					if(res.data.code == 1){
						var MiniProgramMenu=res.data.data.MiniProgramMenu
						if(MiniProgramMenu){
							let MiniProgramMenuEntity=JSON.parse(MiniProgramMenu)
							that.tabbar=MiniProgramMenuEntity.tabs
						}
					}
				});	
			},
			updateApplet(){
				console.log('updateApplet')
				if (wx.canIUse('getUpdateManager')) {
					  const updateManager = wx.getUpdateManager()
					  updateManager.onCheckForUpdate((res)=>{
						// 请求完新版本信息的回调
						if (res.hasUpdate) {
						  updateManager.onUpdateReady(()=>{
							wx.showModal({
							  title: '更新提示',
							  content: '新版本已经准备好，是否重启应用？',
							  success: function (res) {
								// res: {errMsg: "showModal: ok", cancel: false, confirm: true}
								if (res.confirm) {
								  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
								  updateManager.applyUpdate()
								} else if (res.cancel) {
								  //用户点击取消按钮的处理，如果需要强制更新，则给出二次弹窗，如果不需要，则这里的代码都可以删掉了
								  wx.showModal({
									title: '温馨提示~',
									content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦~',
									showCancel: false, //隐藏取消按钮
									confirmText: "确定更新", //只保留确定更新按钮
									success: (res)=>{
									  if (res.confirm) {
										updateManager.applyUpdate()
									  }
									}
								  })
								}
				 
							  }
							})
						  })
						  updateManager.onUpdateFailed(function () {
							// 新的版本下载失败
							wx.showModal({
							  title: '已经有新版本了哟~',
							  content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
							})
						  })
						}
					  })
					}
			},
			setJobStorage(jobId){
				let that=this
				if(jobId!=null&&jobId!=''&&jobId!=undefined){
					let opts = {
						url: 'api/GetQrcodeJobEntity',
						method: 'get'
					};
					let data={
						JobId:jobId
					}
					request.httpTokenALLNotCheckRequest(opts,data).then(res => {
						uni.hideLoading();
						if(res.data.code == 1){
							let entity=res.data.data
							uni.setStorage({
								key:'JobId',
								data:{id:jobId,jobname:entity.JobName,isnfc:entity.isNFC,isImages:entity.isImages,isVideo:entity.isVideo,isDeviceJob:entity.IsDeviceJob},
								success() {
									//修改图片
									if(entity.isNFC===1){
										that.showNFC=true
									}else{
										that.showNFC=false
									}
								}
							})
						}
					});
				}
			},
			// 这个函数 在 onLoad内触发 或 点击触发
			location(){
			    const that = this;
				try
				{
					that.getWxLocation();
			    }
				catch(error)
				{
			        Model({
						title: '温馨提示',
						tip: '获取权限失败，需要获取您的地理位置才能为您提供更好的服务！是否授权获取地理位置？',
						showCancel: true,
						confirmText: '前往设置',
						cancelText: '取消',
			        sureCall(){
			            that.toSetting()
			        },
						cancelCall() {}
			        })
			        return;
			    }
			},
			// 获取位置信息
			getWxLocation() {
				let that=this
				// wx.showLoading({
				//   title: '定位中...',
				//   mask: true,
				// })
			    return new Promise((resolve, reject) => {
			        const _locationChangeFn = (res) => {
			        console.log('location change', res)
				  
				    that.addEntity.Longitude= res.longitude;
				    that.addEntity.Latitude= res.latitude;
					uni.getStorage({
						key: 'JobId',
						success: function (res3) {
							console.log('33')
							that.addEntity.JobId=res3.data.id;
							let opts = {
								url: 'api/AddUserPosition',
								method: 'post'
							};
							request.httpTokenALLNotCheckRequest(opts,that.addEntity).then(res4 => {
								that.getTime()
								if(res4.data.code == 1){
									console.log('上传位置信息success：'+that.nowTime2)
								}
								else{
									console.log('上传位置信息fail')
								}
							});
						},fail() {
						}
				  })
			      wx.hideLoading()
			      wx.offLocationChange(_locationChangeFn)
			    }
			    wx.startLocationUpdate({
			      success: (res) => {
			        wx.onLocationChange(_locationChangeFn)
			        resolve()
			      },
			      fail: (err) => {
			        reject()
			      }
			    })
			  })
			},
			
			// 调起客户端小程序设置界面
			toSetting() {
			  wx.openSetting({
			    success(res) {
			      if (res.authSetting["scope.userLocation"]) {
			        this.authorization()
			      }
			    }
			  })
			},
			//定时上传位置信息
			getIntervalPosition(){
				let that=this
				clearTimeout(that.timer);  
				that.timer=setInterval(()=>{
					//console.log("getIntervalPosition")
					that.location();
				},40000)
			},
			getSceneCount(){
				let that=this
				let opts = {
					url: 'api/getSceneCounts',
					method: 'get'
				};
				request.httpTokenRequest(opts).then(res => {
					if(res.data.code == 1){
						that.counts.SceneCount=res.data.data.SceneCount
					}
				});
			},
			GetSpareCounts(){
				let that=this
				let opts = {
					url: 'SpareApi/GetSpareCounts',
					method: 'get'
				};
				request.httpTokenALLNotCheckRequest(opts).then(res => {
					if(res.data.code == 1){
						that.counts.Outbound=res.data.data.Outbound
						that.counts.yujing=res.data.data.yujing
						that.counts.guoliang=res.data.data.guoliang
						uni.setStorage({
							key:'sparecounts',
							data:that.counts,
							success() {
							}
						})
					}
				});
			},
			ShowNews(e){
				this.PageCur = e;
			},
			NavChange: function(e) {
				let that=this
				console.log('NavChange')
				console.log(e.currentTarget.dataset.cur)
				that.PageCur = e.currentTarget.dataset.cur;
				console.log(that.PageCur)
				uni.setStorage({
					key: 'PageCur',
					data: that.PageCur,
					success: function() {
					}
				});
			},
			NavChange_xd: function() {
				uni.navigateTo({
					url: 'publish',
					animationType: 'slide-in-bottom',
					animationDuration: 200
				});
			},
			getTime: function() {
				var date = new Date(),
					year = date.getFullYear(),
					month = date.getMonth() + 1,
					day = date.getDate(),
					hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
					minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
					second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				month >= 1 && month <= 9 ? (month = "0" + month) : "";
				day >= 0 && day <= 9 ? (day = "0" + day) : "";
				var timer = year + '年' + month + '月' + day + '日';
				var timer2 = hour + ':' + minute + ':' + second;
				this.nowTime = timer;
				this.nowTime2 = timer2;
			},
		}
	}
</script>

<style lang="scss">
	.color_main{
		color: #000000;
		font-weight: 900;
	}
	.box {
		margin: 20upx 0;
	}
	.box view.cu-bar {
		margin-top: 20upx;
	}
	
	.logo_btn{
		width: 44*2rpx;
		height: 44*2rpx;
		position: absolute;
		z-index: 2;
		border-radius: 50%;
		top: -40rpx;
		left: 0rpx;
		right: 0;
		margin: auto;
		padding: 0;
	}
	.cu-bar.tabbar .action.add-action {
	    padding-top: 56rpx !important;
	}
</style>
